﻿using System;
using System.Data;
using System.Web.UI;
using BLL;
using DAL;
using Ext.Net;
using Roles;

namespace ERP.Modules
{
    public partial class CashFund : UserControl
    {
        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetSumCashFund();
                GetCashFund();
                GetSumCashFundReportReceipt();
                ReloadCombox();
                GetAccountBank();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsBank_Account();
            }
        }
        //Store
        protected void StoreCashFund_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxCashFund.Text = string.Empty;
            GetSumCashFund();
            GetCashFund();
            GetAccountBank();
            GetSumCashFundReportReceipt();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            ClearTextBox();
            GetAutoID();
            WindowsCashFund.Show();
            txtCashFund_Name.Focus(false, 100);
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grCashFund.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    ClearTextBox();
                    GetCashFundEdit(int.Parse(row.RecordID));
                    WindowsCashFund.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grCashFund.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtCashFund { ID_CashFund = int.Parse(row.RecordID) };
                        BllCashFund.Delete(obj);
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetCashFund();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsCashFund.Close();
        }
        //Double-Click
        protected void CashFundDblClick(object sender, DirectEventArgs e)
        {
            ClearTextBox();
            int ID_CashFund = int.Parse(e.ExtraParams["ID_CashFund"]);
            GetCashFundEdit(ID_CashFund);
            WindowsCashFund.Show();
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var _clsGetCashFund = new BllCashFund();
            var dtSearch = _clsGetCashFund.CashFundGet(txtSearch.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreCashFund.DataSource = dtSearch;
                StoreCashFund.DataBind();
            }
            else
            {
                grCashFund.GetStore().RemoveAll();
            }
        }
        //Select-Box
        protected void SelectBoxCashFund_Change(object sender, DirectEventArgs e)
        {
            GetCashFund();
        }
        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            ReloadCombox();
        }
        #endregion

        #region[Method]
        private void GetAutoID()
        {
            var _clsCashFund = new BllEmployee();
            var _dtGetAutoID = _clsCashFund.GetAutoID("Cash_Fund_Code", "tb_Cash_Fund");
            if (_dtGetAutoID != null && _dtGetAutoID.Rows.Count > 0)
            {
                try
                {
                    txtCashFund_Name_Code.Text = "QTM-" + DateTime.Now.ToString("yyMM") + "-000" +
                                            Convert.ToString(int.Parse(_dtGetAutoID.Rows[0]["Auto_ID"].ToString()) +
                                                             int.Parse(1.ToString()));
                }
                catch (Exception ex)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                }
            }
        }
        private void GetCashFund()
        {
            if (String.IsNullOrEmpty(SelectBoxCashFund.Text))
            {
                var _clsGetCashFund = new BllCashFund();
                var _dtGetCashFund = _clsGetCashFund.CashFundGet(txtSearch.Text);
                if (_dtGetCashFund != null && _dtGetCashFund.Rows.Count > 0)
                {
                    StoreCashFund.DataSource = _dtGetCashFund;
                    StoreCashFund.DataBind();
                }
                else
                {
                    grCashFund.GetStore().RemoveAll();
                }
            }
            else
            {
                var _clsGetCashFundFillter = new BllCashFund();
                var _dtGetCashFundFillter =
                    _clsGetCashFundFillter.CashFundGetFillter(int.Parse(SelectBoxCashFund.SelectedItem.Value));
                if (_dtGetCashFundFillter != null && _dtGetCashFundFillter.Rows.Count > 0)
                {
                    StoreCashFund.DataSource = _dtGetCashFundFillter;
                    StoreCashFund.DataBind();
                }
                else
                {
                    grCashFund.GetStore().RemoveAll();
                }
            }
        }
        private void GetCashFundEdit(int id)
        {
            var _clsGetCashFund = new BllCashFund();
            var _dtGetCashFundEdit = _clsGetCashFund.CashFundGetEdit(id);
            if (_dtGetCashFundEdit != null && _dtGetCashFundEdit.Rows.Count > 0)
            {
                txtCashFund_ID.Text = _dtGetCashFundEdit.Rows[0]["ID_CashFund"].ToString();
                txtCashFund_Name_Code.Text = _dtGetCashFundEdit.Rows[0]["Cash_Fund_Code"].ToString();
                txtCashFund_Name.Text = _dtGetCashFundEdit.Rows[0]["Cash_Fund_Name"].ToString();
                txtAmount_Original.Text = _dtGetCashFundEdit.Rows[0]["Amount_Original"].ToString();
                txtAmount_Current.Text = _dtGetCashFundEdit.Rows[0]["Amount_Current"].ToString();
                cbCashFundMethod.SetValue(int.Parse(_dtGetCashFundEdit.Rows[0]["Bank_Account_ID"].ToString()));
            }
        }
        private void GetSumCashFund()
        {
            var _clsGetCashFund = new BllCashFund();
            var _dtGetCashFund = _clsGetCashFund.SumCashFund();
            if (_dtGetCashFund != null && _dtGetCashFund.Rows.Count > 0)
            {
                lbToal_Amount_Original.Text = String.Format("{0:0,00}", _dtGetCashFund.Rows[0]["Total_Amount_Original"]).Replace(".", ",");
                //lbTotal_Amount_Current.Text = String.Format("{0:0,00}", _dtGetCashFund.Rows[0]["Total_Amount_Current"]).Replace(".", ",");
            }
        }
        private void GetSumCashFundReportReceipt()
        {
            var _clsGetCashFundReportReceipt = new BllCashFund();
            var _dtGetCashFundReportReceipt = _clsGetCashFundReportReceipt.SumCashFundReportReceipt();
            if (_dtGetCashFundReportReceipt != null && _dtGetCashFundReportReceipt.Rows.Count > 0)
            {
                lbTotal_Amount_Current.Text = String.Format("{0:0,00}", _dtGetCashFundReportReceipt.Rows[0]["Total_Report_Receipt"]).Replace(".", ",");
            }
        }
        private void ReloadCombox()
        {
            var _clsGetBankAccount = new Bank_Account_BLL();
            var _dtGetBankAccount = _clsGetBankAccount.BindGirdtb_Bank_Account(string.Empty);
            if (_dtGetBankAccount != null && _dtGetBankAccount.Rows.Count > 0)
            {
                CashFundMethodStore.DataSource = _dtGetBankAccount;
                CashFundMethodStore.DataBind();
            }
            else
            {
                cbCashFundMethod.GetStore().RemoveAll();
            }
        }
        private void GetAccountBank()
        {
            var _clsGetBankAccount = new Bank_Account_BLL();
            var _dtGetBankAccount = _clsGetBankAccount.BindGirdtb_Bank_Account(string.Empty);
            if (_dtGetBankAccount != null && _dtGetBankAccount.Rows.Count > 0)
            {
                StoreCashFundSelect.DataSource = _dtGetBankAccount;
                StoreCashFundSelect.DataBind();
            }
            else
            {
                SelectBoxCashFund.GetStore().RemoveAll();
            }
        }
        private bool CheckInsert()
        {
            var check = false;
            var _clsCashFundCheck = new BllCashFund();
            var dtCheck = _clsCashFundCheck.CashFundGet(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (txtCashFund_ID.Text != dr["ID_CashFund"].ToString())
                    {
                        if (txtCashFund_Name_Code.Text == dr["Cash_Fund_Code"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã ngân quỹ này đã tồn tại !");
                        }
                        else if (txtCashFund_Name.Text == dr["Cash_Fund_Name"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Tên ngân quỹ này đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (String.IsNullOrEmpty(txtCashFund_ID.Text))
            {
                InsertValue();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateValue();
                }
            }
        }
        private void InsertValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtCashFund
                    {
                        Bank_Account_ID = int.Parse(cbCashFundMethod.SelectedItem.Value),
                        Cash_Fund_Code = txtCashFund_Name_Code.Text,
                        Cash_Fund_Name = txtCashFund_Name.Text,
                        Amount_Original =String.IsNullOrEmpty(txtAmount_Original.Text.Replace(",", "").Replace(".", "")) ? (float?)null : float.Parse(txtAmount_Original.Text.Replace(",", "").Replace(".", "")),
                        Amount_Current = String.IsNullOrEmpty(txtAmount_Current.Text.Replace(",", "").Replace(".", "")) ? (float?)null : float.Parse(txtAmount_Current.Text.Replace(",", "").Replace(".", "")),
                    };
                    BllCashFund.Insert(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công quỹ tiền mặt !");
                    GetCashFund();
                    ClearTextBox();
                    GetAutoID();
                    GetSumCashFund();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtCashFund
                    {
                        ID_CashFund = int.Parse(txtCashFund_ID.Text),
                        Bank_Account_ID = int.Parse(cbCashFundMethod.SelectedItem.Value),
                        Cash_Fund_Code = txtCashFund_Name_Code.Text,
                        Cash_Fund_Name = txtCashFund_Name.Text,
                        Amount_Original = String.IsNullOrEmpty(txtAmount_Original.Text.Replace(",", "").Replace(".", "")) ? (int?)null : int.Parse(txtAmount_Original.Text.Replace(",", "").Replace(".", "")),
                        Amount_Current = String.IsNullOrEmpty(txtAmount_Current.Text.Replace(",", "").Replace(".", "")) ? (int?)null : int.Parse(txtAmount_Current.Text.Replace(",", "").Replace(".", "")),
                    };
                    BllCashFund.Update(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công quỹ tiền mặt !");
                    GetCashFund();
                    GetSumCashFund();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[ClearText]
        private void ClearTextBox()
        {
            txtCashFund_Name_Code.Text = string.Empty;
            txtCashFund_Name.Text = string.Empty;
            txtCashFund_ID.Text = string.Empty;
            txtAmount_Original.Text = string.Empty;
            txtAmount_Current.Text = string.Empty;
            cbCashFundMethod.Text = string.Empty;
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.CashFund, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelCashFund.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.CashFund, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion

        private void WindowsBank_Account()
        {
            Window win = new Window()
            {
                ID = "WindowsBank_Account",
                Title = "Phòng chứa",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Bank_Account.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}